package cm.NewsDaoImpl;

import cm.NewsDao.BaseDao;
import cm.NewsDao.NewsDao2;
import cm.entity.News2;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class NewsDaoImpl2 extends BaseDao implements NewsDao2 {



    @Override
    public List<News2> getNewsList() {
        List<News2> newList=new ArrayList<News2>();
        try {
            //（3）获得Statement对象，执行SQL语句
            String sql="select * from news_category where name like '国%'";
            Object[] params={};
            ResultSet rs=this.executeSQL(sql, params);
            //（4）处理执行结果(ResultSet)，
            while(rs.next()){
                int id=rs.getInt("id");
                String name=rs.getString("name");
                Timestamp time=rs.getTimestamp("createdate");
                //封装成新闻信息对象
                News2 news=new News2();
                news.setId(id);
                news.setName(name);
                news.setCreateDate(time);

                //将新闻对象放进集合中
                newList.add(news);
            }
        }catch (SQLException e) {

            e.printStackTrace();
        }finally{
            //释放资源
            this.closeResource();
        }
        return newList;
    }


    @Override
    //增
    public boolean add(News2 news) {
        boolean flag=false;
        try {
            String sql="insert into news_category(id,name,createdate) values(?,?,?)";
            Object[] params={news.getId(),news.getName(), news.getCreateDate()};
            int i=this.executeUpdate(sql, params);
            //（4）处理执行结果
            if(i>0){
                System.out.println("插入新闻成功！");
            }
            flag=true;
        }finally{
            //释放资源
            this.closeResource();
        }
        return flag;
    }

    @Override
    public boolean delete(int id) {
        boolean flag=false;
        try {
            String sql = "delete from  news_category where id=?";
            Object[] params={};
            int i=this.executeUpdate(sql, params);
            //（4）处理执行结果
            if(i>0){
                System.out.println("删除新闻成功！");
            }
            flag=true;
        }  finally {
            //释放资源
            this.closeResource();
        }
        return flag;
    }

    @Override
    public boolean update(News2 news) {
        boolean flag=false;
        try {
            String sql = "update News_category set name=? where id=?";
            Object[] params={news.getName(),news.getId()};
            int i=this.executeUpdate(sql, params);
            //（4）处理执行结果
            if(i>0){
                System.out.println("修改新闻成功！");
            }
            flag=true;
        }  finally {
            //释放资源
            this.closeResource();
        }
        return flag;
    }
}
